package servlet;

import dao.UserDAO;
import dao.UserDAO1;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "useradd", value = "/user/add")
public class UserAddServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置post请求参数乱码问题
        System.out.println(123123131);
        req.setCharacterEncoding("UTF-8");
        // 接收请求参数
        String username = req.getParameter("username");
        String age = req.getParameter("age");
        String mobile = req.getParameter("mobile");
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String status = req.getParameter("status");

        // 将字符串转换为整数
        int ageInt = Integer.parseInt(age.trim());
        int statusInt = Integer.parseInt(status.trim());

        // 封装成一个User对象
        User user = new User();
        user.setUsername(username);
        user.setAge(ageInt);
        user.setMobile(mobile);
        user.setEmail(email);
        user.setAddress(address);
        user.setStatus(statusInt);
        user.setPassword("123456");

        // 创建dao
        UserDAO1 userDAO1 = new UserDAO1();
        userDAO1.insert(user);

        System.out.println(user);
        System.out.println("用户" + username + "添加成功");

        // 重定向
        resp.sendRedirect("/Mall/user/list");
    }
}
